package org.graduates.webapp.actions.person;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.graduates.webapp.actions.BaseAction;
import org.projects.graduates.Constants;
import org.projects.graduates.domain.Person;
import org.projects.graduates.utils.FileCommon;

/**
 * 上传头像
 * 
 * @author Administrator
 * 
 */

@Action(results = { @Result(name = "success", type = "json") })
public class UploadPortraitAction extends BaseAction {

	private static final long serialVersionUID = -976374706064422813L;

	private File img;

	private String imgFileName;

	private String error;

	public String execute() {

		if (null == img) {
			error = "文件不能为空";
			return SUCCESS;
		}

		String ext = FileCommon.extOf(imgFileName);
		try {
			String port_temp = where() + "portrait_temp." + ext;
			String port = where() + "portrait." + ext;
			FileCommon.write(img, "portrait_temp." + ext, where());
			BufferedImage originalImage = ImageIO.read(new File(port_temp));
			resetPortrait();
			Thumbnails.of(originalImage).size(55, 55).toFile(new File(port));
			FileCommon.delFile(where() + "portrait_temp." + ext);
			Person pp = getCurrentPerson();
			pp.setHeadPortrait(headUrl("portrait." + ext));
			this.gradApplication.save(pp);
		} catch (IOException e) {
			e.printStackTrace();
			error = "数据传送失败";
			return SUCCESS;
		}
		return SUCCESS;
	}

	// 删除已有头像
	private void resetPortrait() {
		File space = new File(where());
		for(File f : space.listFiles()){
			if(f.getName().matches("^portrait\\.*?[.](jpg|gif|png|JPG|GIF|PNG)")){
				f.delete();
			}
		}
	}

	private String where() {
		String result = ServletActionContext.getServletContext().getRealPath(Constants.UPLOAD_DIR) + File.separator
				+ getCurrentPersonId() + File.separator;
		return result;
	}

	private String headUrl(String imgPath) {
		String result = ServletActionContext.getServletContext().getContextPath() + "/" + Constants.UPLOAD_DIR;
		result += "/" + getCurrentPersonId() + "/" + imgPath;
		return result;
	}

	public void setImg(File img) {
		this.img = img;
	}

	public String getError() {
		return error;
	}

	public String getImgFileName() {
		return imgFileName;
	}

	public void setImgFileName(String imgFileName) {
		this.imgFileName = imgFileName;
	}

}
